<template>
  <a-card :bordered="false" class="card-area">
    <div style="padding: 8px;margin-bottom:50px">
      <a-form-model :model="searchForm" ref="searchForm">
        <a-row>
          <a-col :span="10">
            <a-form-model-item
              label="法人行标识"
              prop="instId"
              :labelCol="{ span: 8 }"
              :wrapperCol="{ span: 15 }"
            >
              <a-select
                v-model="searchForm.instId"
                allowClear
                @change="handleIDChange"
                placeholder='法人行标识'
              >
                <a-select-option
                  v-for="(item, index) in instList"
                  :key="index"
                  :value="item.instId"
                  >{{ item.instName }}</a-select-option
                >
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="10">
            <a-form-model-item label='清算日期' prop='settleDate'  :labelCol="{ span: 8 }" :wrapperCol="{ span: 15 }">
              <a-date-picker v-model="searchForm.settleDate" allowClear @change="onChange"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="4" style="margin-top: 3px; position: relative;left:-585px;top:35px;margin-top: 30px;">
            <a-button type="primary" @click="search" :disabled='isDisabled'>查询</a-button>
            <a-button @click="reset">重置</a-button>
          </a-col>
        </a-row>
      </a-form-model>
    </div>
    <a-layout class="container">
      <a-layout-sider :width="siderLeftWid" theme="light" class="select-area">
        <a-select v-model="treeList" @change="onChange1" show-search :filter-option="filterOption1" allowClear style="width: 96%;margin:0 5px;" placeholder="请输入节点名称">
          <a-select-option v-for="(i, e) in field.commonNodes" :key="e" :value='i.settleAcctDesc'>{{i.settleAcctDesc}}</a-select-option>
        </a-select>
        <a-row v-show="searchForm.instId !== ''">
          <div align="center">
            <a-list :grid="{ gutter: 8, column: 2 }">
              <a-list-item v-for="(commonNode, index) in field.commonNodes" :key="index" style="width: 100%;height:36px;">
                <div class="node-item" :type="commonNode.type" belongto="commonNodes" @mousedown="nodeMove(commonNode)">
                  <span style="font-size:12px;">{{commonNode.settleAcctDesc}}</span>
                </div>
              </a-list-item>
            </a-list>
          </div>
        </a-row>
      </a-layout-sider>
      <a-layout>
        <a-layout-header class="header-option" style="padding: 0 10px;">
          <span v-for="(i, j) in field.tools" :key="j">
              <a-button class="header-option-button" @click="selectTool(i.type)" :icon="i.icon" size="small" :style="{color: i.colorIcon}">
                {{i.name}}
              </a-button>
          </span>
          <a-tooltip title="保存流程" placement="bottom">
            <a-button
              @click="saveFlow"
              :disabled='isSave'
              class="header-option-button"
              size="small"
              icon="save"
            >保存流程</a-button>
          </a-tooltip>
          <a-popconfirm
            title="确认要重新绘制吗？"
            placement="bottom"
            okText="确认"
            cancelText="取消"
            @confirm="clear"
          >
            <a-tooltip title="重新绘制" placement="bottom">
              <a-button
                class="header-option-button"
                size="small"
                icon="delete"
              >重新绘制</a-button>
            </a-tooltip>
          </a-popconfirm>
          <a-popconfirm
            title="请选择帮助项："
            placement="bottom"
            okType="default"
            okText="快捷键大全"
            cancelText="使用文档"
            @confirm="shortcutHelper"
          >
            <a-icon slot="icon" type="question-circle-o" style="color: red" />
            <a-tooltip title="帮助" placement="bottom">
              <a-button
                class="header-option-button"
                size="small"
                icon="book"
              >帮助</a-button>
            </a-tooltip>
          </a-popconfirm>
          <a-tooltip title="全屏" placement="bottom">
            <a-button class="header-option-button" size="small" :icon="fullscreen===false?'fullscreen':'fullscreen-exit'" @click="getFullscreen">全屏</a-button>
          </a-tooltip>
        </a-layout-header>
        <a-layout-content class="content" :style="{height: eleHeight}">
          <flow-area
            ref="flowArea"
            :browserType="browserType"
            :flowData="flowData"
            :select.sync="currentSelect"
            :selectGroup.sync="currentSelectGroup"
            :plumb="plumb"
            :currentTool="currentTool"
            @findNodeConfig="findNodeConfig"
            @selectTool="selectTool"
            @getShortcut="getShortcut"
            @saveFlow="saveFlow"
          >
          </flow-area>
          <vue-context-menu
            :contextMenuData="linkContextMenuData"
            @deleteLink="deleteLink"
          >
          </vue-context-menu>
        </a-layout-content>
      </a-layout>
      <!-- <a-layout-sider
        :width="0"
        theme="light"
        class="attr-area"
        @mousedown.stop="loseShortcut"
      >
        <flow-attr
          :plumb="plumb"
          :flowData="flowData"
          :select.sync="currentSelect"
          ref="selectForm"
        ></flow-attr>
      </a-layout-sider> -->
    </a-layout>
    <setting-modal ref="settingModal"></setting-modal>
    <shortcut-modal ref="shortcutModal"></shortcut-modal>
    <test-modal ref="testModal" @loadFlow="loadFlow"></test-modal>
    <a-modal v-model="isVisible" title="进度信息" :footer='null'>
      <a-table :current="1" :columns="columns" :data-source="dataSource" :pagination='pagination' :rowKey="(record,index)=>{return index}" bordered></a-table>
    </a-modal>
  </a-card>
</template>

<script>
import jsplumb from 'jsplumb'
import {
  tools1,
  commonNodes,
  highNodes,
  laneNodes,
} from '@/utils/basic-node-config.js'
import { flowConfig } from '@/utils/args-config.js'
import $ from 'jquery'
import 'jquery-ui/ui/widgets/draggable'
import 'jquery-ui/ui/widgets/droppable'
import 'jquery-ui/ui/widgets/resizable'
import html2canvas from 'html2canvas'
import canvg from 'canvg'
import { eventMethod } from '@/utils/eventMethod'
import FlowArea from '@/components/flowControlModal/FlowAreMonitor'
// import FlowArea from '@/components/flowControlModal/FlowArea'
import FlowAttr from '@/components/flowControlModal/FlowAttr'
import SettingModal from '@/components/flowControlModal/SettingModal'
import ShortcutModal from '@/components/flowControlModal/ShortcutModal'
import TestModal from '@/components/flowControlModal/TestModal'

export default {
  name: 'vfd',
  components: {
    jsplumb,
    flowConfig,
    html2canvas,
    canvg,
    FlowArea,
    FlowAttr,
    SettingModal,
    ShortcutModal,
    TestModal,
  },
  created () {
    this.getList()
  },
  mounted () {
    this.dealCompatibility() // 浏览器兼容性
    this.initNodeSelectArea() // 初始化节点模块
    this.initJsPlumb() // 实例化JsPlumb
    this.listenShortcut() // 初始化快捷键
    this.initFlow() // 初始化流程图
    // this.listenPage() // 关闭提示
    document.body.onkeydown = function (event) {
      var e = window.event || event
      if (e.keyCode === 32) {
        return false
      }
    }
    let timer
    clearInterval(timer)
    timer = setInterval(() => {
      this.getList()
      console.log('30000毫秒调用一次')
    }, 30000)
  },
  data () {
    return {
      isSave: false,
      isDisabled: false,
      fullscreen: false,
      eleHeight: '350px',
      searchForm: {
        bizType: '',
        txnNum: '',
        transChannelId: '',
        msgSrcId: '',
        instId: '',
        settleDate: ''
      },
      instList: [],
      msgSrcChannelInfoList: [],
      transChannelInfoList: [],
      transChannelTxnInfoList: [],
      channelServiceInfoList: [],
      selectNodeObj: {},
      listNodes: [],
      treeList: undefined,
      siderLeftWid: 0,
      showRightSider: false,
      tag: {
        checked1: true
      },
      browserType: 3,
      plumb: {},
      field: {
        tools: tools1,
        commonNodes: [],
        // commonNodes: commonNodes,
        highNodes: highNodes,
        laneNodes: laneNodes,
      },
      flowData: {
        nodeList: [],
        linkList: [],
        attr: {
          id: '',
        },
        config: {
          showGrid: false,
          showGridText: '显示网格',
          showGridIcon: 'eye-invisible',
        },
        status: flowConfig.flowStatus.CREATE,
        remarks: [],
      },
      currentTool: {
        type: 'drag',
        icon: 'drag',
        name: '拖拽',
      },
      currentSelect: {},
      currentSelectGroup: [],
      activeShortcut: true,
      linkContextMenuData: flowConfig.contextMenu.link,
      connTypes: '',
      bizScene: '',
      bizSceneDesc: '',
      listArr: [],
      isVisible: false,
      columns: [
        {
          dataIndex: 'bizProdType',
          title: '业务产品类型',
          align: 'center',
          customRender: (code, rows, index) => {
            switch (code) {
              case '01':
                return '银联CUPS受理侧'
              case '02':
                return '微信支付'
              case '03':
                return '支付宝支付'
              case '04':
                return '分期'
              case '05':
                return '积分'
              case '06':
                return '银联小微二维码'
              case '07':
                return '网联受理侧'
              case '08':
                return '本行渠道业务'
              case '11':
                return '银联助农业务'
              case '21':
                return '银联线上支付'
              case '22':
                return '银联无卡快捷受理侧'
              case '23':
                return '银联全渠道-代付'
              case '24':
                return '银联全渠道-无跳转'
              case '25':
                return '银联全渠道-代收'
              case '26':
                return '深圳银联业务'
              case '27':
                return '厦门银联业务'
              case '31':
                return '银联二维码'
              case '40':
                return '提现'
              case '41':
                return '商户入账失败挂账'
              case '42':
                return '风险资金挂账'
              case '43':
                return '商户风险资金入账失败挂账'
              case '44':
                return '代理商分润'
              case '45':
                return '营销'
              case '46':
                return 'D0补入账'
              case '*':
                return '所有业务类型'
              default:
                return code
            }
          }
        },
        {
          dataIndex: 'settleAmt',
          title: '清算金额',
          align: 'center'
        },
        {
          dataIndex: 'acctStatus',
          title: '清算状态',
          align: 'center',
          customRender: (code, rows, index) => {
            switch (code) {
              case '00':
                return '待记账'
              case '01':
                return '记账成功'
              case '02':
                return '记账失败'
              case '03':
                return '小于等于虚拟账户余额可入账'
              case '04':
                return '大于虚拟账户余额不可入账'
              case '05':
                return '当日大于虚拟账户余额后续可以入账'
              case '06':
                return '提现金额大于入账金额，不可入账'
              case '07':
                return '提现金额大于入账金额，后续已累加，此笔记录不再处理'
              case '10':
                return '暂缓记账'
              case '11':
                return '取消全部暂缓记账待记账'
              case '12':
                return '取消全部暂缓记账记账成功'
              case '13':
                return '取消全部暂缓记账记账失败'
              case '20':
                return '收支两线商户手续费扣账失败机构手续费收益暂缓记账'
              case '31':
                return '记账失败重新记账成功'
              default:
                return code
            }
          }
        }
      ],
      dataSource: [],
      pagination: {
        defaultCurrent: 1,
        defaultPageSize: 5,
        size: 'small',
        showTotal: total => `共 ${total} 条记录`
      }
    }
  },
  methods: {
    onChange (date, dateString) {
      let str = []
      str = dateString.split('-')
      this.searchForm.settleDate = str.join('')
    },
    getList () {
      // 获取法人行列表
      this.$get(`admin/viewLinkCfg/instList`).then((res) => {
        if (res.status === 200) {
          this.instList = res.data.instInfoList
        }
      })
    },
    // 法人行标识
    handleIDChange (val) {
      let dataId
      if (val === undefined) {
        dataId = ''
        this.treeList = undefined
      } else {
        dataId = val
      }
      // 资金流转监控
      this.$get('/admin/viewLinkCfg/roleAcctQuery', {instId: dataId}).then(res => {
        if (res.data.roleAcctInfoList.length === 0) {
          this.siderLeftWid = 0
        } else {
          this.siderLeftWid = 210
        }
        res.data.roleAcctInfoList.forEach((i) => {
          i.type = 'common'
        })
        // 节点模块分组显示
        this.field.commonNodes = res.data.roleAcctInfoList
        this.initNodeSelectArea()
      })
    },
    onChange1 (val) {
      if (val === undefined) {
        this.handleIDChange(this.searchForm.instId)
      } else {
        let nodeArr = []
        for (let index = 0; index < this.field.commonNodes.length; index++) {
          const element = this.field.commonNodes[index]
          if (element.settleAcctDesc === val) {
            nodeArr.push(element)
          }
        }
        this.field.commonNodes = nodeArr
      }
    },
    // 鼠标移动携带参数
    nodeMove (commonNode) {
      this.selectNodeObj = commonNode
      commonNodes.forEach((item) => {
        if (item.type === 'common') {
          item.nodeName = commonNode.settleAcctDesc
        }
      })
    },
    filterOption1 (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    // 查询
    search () {
      this.isDisabled = true
      setTimeout(() => {
        this.isDisabled = false
      }, 2000)
      if (this.searchForm.instId === '' || this.searchForm.settleDate === '') {
        this.$message.info('请选择完成之后再查询！')
      } else {
        let params = {
          viewType: '01',
          instId: this.searchForm.instId,
          bizType: 'UPMP',
          msgSrcId: 'UPMP',
          transChannelId: 'UPMP',
          txnNum: 'UPMP',
          settleDate: this.searchForm.settleDate
        }
        this.clear()
        this.$get(`admin/viewLinkCfg/transLinkCfgInfoQuery`, params).then((res) => {
          if (res.status === 200) {
            this.$message.success('查询成功！')
            this.loadFlow(res.data.transLinkCfgInfo)
          }
        }).catch((r) => {
          this.$message.error('没有查询到数据,请创建新的流程!')
        })
      }
    },
    // 重置
    reset () {
      this.$refs.searchForm.resetFields()
      this.siderLeftWid = 0
      this.eleHeight = '350px'
      this.clear()
      this.flowData.nodeList = []
    },
    getBrowserType () {
      let userAgent = navigator.userAgent
      let isOpera = userAgent.indexOf('Opera') > -1
      if (isOpera) {
        return 1
      }
      if (userAgent.indexOf('Firefox') > -1) {
        return 2
      }
      if (userAgent.indexOf('Chrome') > -1) {
        return 3
      }
      if (userAgent.indexOf('Safari') > -1) {
        return 4
      }
      if (
        userAgent.indexOf('compatible') > -1 &&
        userAgent.indexOf('MSIE') > -1 &&
        !isOpera
      ) {
        alert('IE浏览器支持性较差，推荐使用Firefox或Chrome')
        return 5
      }
      if (userAgent.indexOf('Trident') > -1) {
        alert('Edge浏览器支持性较差，推荐使用Firefox或Chrome')
        return 6
      }
    },
    dealCompatibility () {
      this.browserType = this.getBrowserType()
      if (this.browserType === 2) {
        flowConfig.shortcut.scaleContainer = {
          code: 16,
          codeName: 'SHIFT(chrome下为ALT)',
          shortcutName: '画布缩放',
        }
      }
    },
    initJsPlumb () {
      this.plumb = jsplumb.jsPlumb.getInstance(flowConfig.jsPlumbInsConfig)
      this.plumb.bind('beforeDrop', (info) => {
        // 连接线业务相同的线只有一条
        let filter = this.flowData.linkList.filter(link => (link.sourceId === info.sourceId && link.targetId === info.targetId))
        for (let index = 0; index < filter.length; index++) {
          const ele = filter[index]
          if (ele.type === this.connTypes) {
            this.$message.error('两节点之间业务相同的连线只能有一条！')
            return false
          }
        }
        // 避免连线源锚点和目标锚点在同一节点上
        if (info.sourceId === info.targetId) return false
        return true
      })
      this.plumb.bind('connection', (conn, e) => {
        let connObj = conn.connection.canvas
        let o = {}
        let id
        let label
        if (
          this.flowData.status === flowConfig.flowStatus.CREATE ||
          this.flowData.status === flowConfig.flowStatus.SAVE
        ) {
          id = this.connTypes + '-' + eventMethod.getId()
          label = ''
        } else if (this.flowData.status === flowConfig.flowStatus.LOADING ||
          this.flowData.status === flowConfig.flowStatus.MODIFY) {
          let l = this.flowData.linkList[this.flowData.linkList.length - 1]
          id = l.id
          label = l.label
        }
        connObj.id = id
        o.type = this.connTypes
        o.id = id
        o.label = label
        o.sourceId = conn.sourceId
        o.targetId = conn.targetId
        o.bizScene = this.bizScene
        o.bizSceneDesc = this.bizSceneDesc
        o.cls = {
          linkType: flowConfig.jsPlumbInsConfig.Connector[0],
          linkColor: flowConfig.jsPlumbInsConfig.PaintStyle.stroke,
          linkThickness: flowConfig.jsPlumbInsConfig.PaintStyle.strokeWidth,
        }
        // 显示菜单
        $('#' + id).bind('contextmenu', (e) => {
          this.showLinkContextMenu(e)
          this.currentSelect = this.flowData.linkList.filter(
            (l) => l.id === id
          )[0]
        })
        // 单击连接线
        $('#' + id).bind('click', (e) => {
          let event = window.event || e
          event.stopPropagation()
          this.flowData.linkList.forEach((item, index) => {
            if (item.id === id) {
              this.currentSelect = item
              if (item.percent !== undefined && item.percent !== '0.00%') {
                this.isVisible = true
                this.dataSource = item.settleInstructionList
                console.log(item, 'item', this.fullscreen)
              }
            }
          })
        })
        if (this.flowData.status !== flowConfig.flowStatus.LOADING) { this.flowData.linkList.push(o) }
      })
      this.plumb.importDefaults({
        ConnectionsDetachable: flowConfig.jsPlumbConfig.conn.isDetachable,
      })
    },
    initNodeSelectArea () {
      $(document).ready(() => {
        $('.node-item').draggable({
          opacity: flowConfig.defaultStyle.dragOpacity,
          helper: 'clone',
          cursorAt: {
            top: 16,
            left: 60,
          },
          containment: 'window',
          revert: 'invalid',
        })
      })
    },
    // 键盘监听事件
    listenShortcut () {
      document.onkeydown = (e) => {
        let event = window.event || e
        if (!this.activeShortcut) return
        let key = event.keyCode
        switch (key) {
          case flowConfig.shortcut.multiple.code:
            this.$refs.flowArea.rectangleMultiple.flag = true
            break
          case flowConfig.shortcut.dragContainer.code:
            this.$refs.flowArea.container.dragFlag = true
            break
          case flowConfig.shortcut.scaleContainer.code:
            this.$refs.flowArea.container.scaleFlag = true
            break
          case flowConfig.shortcut.dragTool.code:
            this.selectTool('drag')
            break
          case flowConfig.shortcut.connTool.code:
            if (this.$refs.selectForm.visible === false) {
              this.selectTool('connScene')
            }
            break
          case flowConfig.shortcut.zoomInTool.code:
            this.selectTool('zoom-in')
            break
          case flowConfig.shortcut.zoomOutTool.code:
            this.selectTool('zoom-out')
            break
          case flowConfig.shortcut.delNode.code:
            if (this.$refs.selectForm.visible === false) {
              if (this.$refs.selectForm.activeKey === 'link-attr') {
                this.deleteLink()
              } else if (this.$refs.selectForm.activeKey === 'node-attr') {
                this.$refs.flowArea.deleteNode()
              }
            }
            break
          case 37:
            this.moveNode('left')
            break
          case 38:
            this.moveNode('up')
            break
          case 39:
            this.moveNode('right')
            break
          case 40:
            this.moveNode('down')
            break
          case 27:
            this.fullscreen = false
            // this.checkFull()
            // this.getFullscreen()
            break
        }
        if (event.ctrlKey) {
          if (event.altKey) {
            switch (key) {
              case flowConfig.shortcut.settingModal.code:
                this.setting()
                break
              case flowConfig.shortcut.testModal.code:
                this.openTest()
                break
            }
          }
        }
      }
      document.onkeyup = (e) => {
        let event = window.event || e
        let key = event.keyCode
        if (key === flowConfig.shortcut.dragContainer.code) {
          this.$refs.flowArea.container.dragFlag = false
        } else if (key === flowConfig.shortcut.scaleContainer.code) {
          event.preventDefault()
          this.$refs.flowArea.container.scaleFlag = false
        } else if (key === flowConfig.shortcut.multiple.code) {
          this.$refs.flowArea.rectangleMultiple.flag = false
        }
      }
    },
    // 刷新页面提示是否重新加载
    listenPage () {
      window.onbeforeunload = (e) => {
        e = e || window.event
        if (e) {
          e.returnValue = '关闭提示'
        }
        return '关闭提示'
      }
    },
    initFlow () {
      if (this.flowData.status === flowConfig.flowStatus.CREATE) {
        this.flowData.attr.id = 'flow-' + eventMethod.getId()
      } else {
        this.loadFlow()
      }
    },
    loadFlow (loadData) {
      this.flowData.attr = loadData.attr
      this.flowData.config = loadData.config
      if (loadData.config.showGrid === 'false') {
        this.flowData.config.showGrid = false
      } else {
        this.flowData.config.showGrid = true
      }
      this.flowData.status = flowConfig.flowStatus.MODIFY
      this.flowData.remarks = loadData.remarks
      this.plumb.batch(() => {
        let nodeList = loadData.nodeList
        nodeList.forEach((node, index) => {
          this.flowData.nodeList.push(node)
        })
        let linkList = loadData.typeList
        this.$nextTick(() => {
          linkList.forEach((link, index) => {
            this.listArr.push(link)
            this.flowData.linkList.push(link)
            // this.dataSource = link.settleInstructionList
            this.connTypes = link.type
            let pat = ''
            if (link.percent === '100.00%') {
              pat = 'red'
              // pat = '#85FF0A'
            } else if (link.percent !== '0.00%') {
              // pat = '#FFA500'
              pat = '#008000'
            } else {
              pat = link.cls.linkColor
            }
            let conn = this.plumb.connect({
              percent: link.percent,
              bizScene: link.bizScene,
              bizSceneDesc: link.bizSceneDesc,
              source: link.sourceId,
              target: link.targetId,
              anchor: flowConfig.jsPlumbConfig.anchor.default,
              connector: [
                link.cls.linkType,
                {
                  gap: 5,
                  cornerRadius: 8,
                  alwaysRespectStubs: true,
                },
              ],
              paintStyle: {
                stroke: pat,
                // stroke: link.cls.linkColor,
                strokeWidth: 2.5
              },
            })
            if (link.percent !== '') {
              conn.setLabel({
                label: link.percent,
                cssClass: 'linkLabel',
              })
            }
          })
          this.flowData.linkList = this.listArr
          // let arr1 = linkList
          // let arr2 = []
          // for (let i = 0; i < arr1.length; i++) {
          //   const element = arr1[i]
          //   for (let j = 0; j < this.listArr.length; j++) {
          //     const ele = this.listArr[j]
          //     console.log(element.id, '===', ele.id)
          //     if (element.id === ele.id) {
          //       arr2.push(ele)
          //     }
          //   }
          // }
          // this.flowData.linkList = arr2
          this.currentSelect = {}
          this.currentSelectGroup = []
          this.flowData.status = loadData.status
        })
      }, true)
      let canvasSize = this.computeCanvasSize()
      this.$refs.flowArea.container.pos = {
        top: -canvasSize.minY + 100,
        left: -canvasSize.minX + 100,
      }
    },
    findNodeConfig (belongto, type, callback) {
      let node = null
      switch (belongto) {
        case 'commonNodes':
          node = commonNodes.filter((n) => n.type === type)
          Object.assign(node[0], this.selectNodeObj)
          break
        case 'highNodes':
          node = highNodes.filter((n) => n.type === type)
          break
        case 'laneNodes':
          node = laneNodes.filter((n) => n.type === type)
          break
      }
      if (node && node.length >= 0) node = node[0]
      callback(node)
    },
    selectTool (type) {
      this.connTypes = type
      let tool = tools1.filter((t) => t.type === type)
      if (tool && tool.length >= 0) this.currentTool = tool[0]
      switch (type) {
        case 'drag':
          this.changeToDrag()
          break
        case 'connScene':
          if (this.flowData.nodeList.length !== 0) {
            this.changeToConnection()
          }
          break
        case 'zoom-in':
          this.changeToZoomIn()
          break
        case 'zoom-out':
          this.changeToZoomOut()
          break
      }
    },
    changeToDrag () {
      this.flowData.nodeList.forEach((node, index) => {
        let f = this.plumb.toggleDraggable(node.id)
        if (!f) {
          this.plumb.toggleDraggable(node.id)
        }
        if (node.type !== 'x-lane' && node.type !== 'y-lane') {
          this.plumb.unmakeSource(node.id)
          this.plumb.unmakeTarget(node.id)
        }
      })
    },
    changeToConnection () {
      this.flowData.nodeList.forEach((node, index) => {
        let f = this.plumb.toggleDraggable(node.id)
        if (f) {
          this.plumb.toggleDraggable(node.id)
        }
        if (node.type !== 'x-lane' && node.type !== 'y-lane') {
          this.plumb.unmakeSource(node.id)
          this.plumb.unmakeTarget(node.id)
          this.plumb.makeSource(
            node.id,
            flowConfig.jsPlumbConfig.makeSourceConfig
          )
          this.plumb.makeTarget(
            node.id,
            flowConfig.jsPlumbConfig.makeTargetConfig
          )
        }
      })
      this.currentSelect = {}
      this.currentSelectGroup = []
    },
    changeToZoomIn () {
      console.log('切换到放大工具')
    },
    changeToZoomOut () {
      console.log('切换到缩小工具')
    },
    checkFlow () {
      let nodeList = this.flowData.nodeList
      if (nodeList.length <= 0) {
        this.$message.error('流程图中无任何节点！')
        return false
      }
      return true
    },
    saveFlow () {
      let flowObj = Object.assign({}, this.flowData)
      if (!this.checkFlow()) return
      this.isSave = true
      setTimeout(() => {
        this.isSave = false
      }, 2000)
      flowObj.status = flowConfig.flowStatus.SAVE
      let dataParams = {
        viewType: '01',
        instId: this.searchForm.instId,
        bizType: 'UPMP',
        msgSrcId: 'UPMP',
        transChannelId: 'UPMP',
        txnNum: 'UPMP',
        // bizType: this.searchForm.txnNum.slice(0, 2),
        // msgSrcId: this.searchForm.msgSrcId,
        // transChannelId: this.searchForm.transChannelId,
        // txnNum: this.searchForm.txnNum.slice(2),
        transLinkCfgInfo: {
          attr: {},
          config: {},
          nodeList: [],
          remarks: [],
          typeList: [],
        },
      }
      dataParams.transLinkCfgInfo.attr.id = flowObj.attr.id
      dataParams.transLinkCfgInfo.config.showGrid = flowObj.config.showGrid
      dataParams.transLinkCfgInfo.config.showGridIcon =
        flowObj.config.showGridIcon
      dataParams.transLinkCfgInfo.config.showGridText =
        flowObj.config.showGridText
      dataParams.transLinkCfgInfo.nodeList = flowObj.nodeList
      dataParams.transLinkCfgInfo.status = flowObj.status
      dataParams.transLinkCfgInfo.typeList = flowObj.linkList
      console.log(this.flowData.linkList, 'this.flowData.linkList', flowObj.linkList)
      console.log(dataParams, 'dataParams')
      this.$postJson('admin/viewLinkCfg/transLinkCfg', dataParams).then((res) => {
        if (res.status === 200) {
          this.$message.success('保存成功！')
        }
      }).catch((r) => {
        this.$message.error(r.response.data.message)
      })
    },
    computeCanvasSize () {
      let nodeList = Object.assign([], this.flowData.nodeList)
      let minX = nodeList[0].x
      let minY = nodeList[0].y
      let maxX = nodeList[0].x + nodeList[0].width
      let maxY = nodeList[0].y + nodeList[0].height
      nodeList.forEach((node, index) => {
        minX = Math.min(minX, node.x)
        minY = Math.min(minY, node.y)
        maxX = Math.max(maxX, node.x + node.width)
        maxY = Math.max(maxY, node.y + node.height)
      })
      let canvasWidth = maxX - minX
      let canvasHeight = maxY - minY
      return {
        width: canvasWidth,
        height: canvasHeight,
        minX: minX,
        minY: minY,
        maxX: maxX,
        maxY: maxY,
      }
    },
    clear () {
      this.flowData.nodeList.forEach((node, index) => {
        this.plumb.remove(node.id)
      })
      this.flowData.linkList.forEach((link, i) => {
        this.plumb.deleteConnection(
          this.plumb.getConnections({
            source: link.sourceId,
            target: link.targetId,
          })[i]
        )
      })
      this.currentSelect = {}
      this.currentSelectGroup = []
      this.flowData.nodeList = []
      this.flowData.linkList = []
      this.flowData.remarks = []
      this.bizScene = ''
      this.bizSceneDesc = ''
    },
    setting () {
      this.$refs.settingModal.open()
    },
    shortcutHelper () {
      this.$refs.shortcutModal.open()
    },
    // 全屏
    getFullscreen (element1) {
      console.log(element1, 'flowContainer', document.documentElement)
      console.log(document.getElementById('flowContainer'), 'container', document.getElementsByClassName('ant-card-body'))
      console.log(document.getElementsByClassName('ant-modal-root')[0])
      if (this.siderLeftWid !== 0) {
        // let element = $('.card-area')[0] // 带搜索栏
        // let element = $('.content')[0] // 不包括工具栏
        let element = $('.container')[0]
        // const element = document.documentElement || $('.container')[0]
        // const element = document.body
        if (this.fullscreen) {
          if (document.exitFullscreen) {
            document.exitFullscreen()
          } else if (document.webkitCancelFullScreen) {
            document.webkitCancelFullScreen()
          } else if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen()
          } else if (document.msExitFullscreen) {
            document.msExitFullscreen()
          }
        } else {
          if (element.requestFullscreen) {
            element.requestFullscreen()
          } else if (element.webkitRequestFullScreen) {
            element.webkitRequestFullScreen()
          } else if (element.mozRequestFullScreen) {
            element.mozRequestFullScreen()
          } else if (element.msRequestFullscreen) {
            // IE11
            element.msRequestFullscreen()
          }
        }
        this.fullscreen = !this.fullscreen
        window.onresize = () => {
          if (!this.checkFull()) {
            this.fullscreen = false // 恢复图标
          }
        }
      }
    },
    checkFull () {
      let isFull = document.fullscreenEnabled || window.fullScreen || document.webkitIsFullScreen || document.msFullscreenEnabled
      if (isFull === undefined) isFull = false
      return isFull
    },
    // 显示连接线菜单
    showLinkContextMenu (e) {
      let event = window.event || e
      event.preventDefault()
      event.stopPropagation()
      $('.vue-contextmenuName-flow-menu').css('display', 'none')
      $('.vue-contextmenuName-node-menu').css('display', 'none')
      let x = event.clientX
      let y = event.clientY
      this.linkContextMenuData.axis = { x, y }
    },
    // 删除连线
    deleteLink () {
      let sourceId = this.currentSelect.sourceId
      let targetId = this.currentSelect.targetId
      this.plumb.deleteConnection(
        this.plumb.getConnections({
          source: sourceId,
          target: targetId,
        })[0]
      )
      let linkList = this.flowData.linkList
      linkList.splice(
        linkList.findIndex(
          (link) => link.sourceId === sourceId || link.targetId === targetId
        ),
        1
      )
      this.currentSelect = {}
    },
    // 点击属性栏
    loseShortcut () {
      this.activeShortcut = false
    },
    // 当画图区域有元素时显示
    getShortcut () {
      this.activeShortcut = true
    },
    openTest () {
      let flowObj = Object.assign({}, this.flowData)
      this.$refs.testModal.flowData = flowObj
      this.$refs.testModal.testVisible = true
    },
    moveNode (type) {
      let m = flowConfig.defaultStyle.movePx
      let isX = true
      switch (type) {
        case 'left':
          m = -m
          break
        case 'up':
          m = -m
          isX = false
          break
        case 'right':
          break
        case 'down':
          isX = false
      }
      if (this.currentSelectGroup.length > 0) {
        this.currentSelectGroup.forEach((node, index) => {
          if (isX) {
            node.x += m
          } else {
            node.y += m
          }
        })
        this.plumb.repaintEverything()
      } else if (this.currentSelect.id) {
        if (isX) {
          this.currentSelect.x += m
        } else {
          this.currentSelect.y += m
        }
        this.plumb.repaintEverything()
      }
    },
  },
}
</script>

<style lang="less" scoped>
@import "../../../static/less/flow-designer.less";
</style>
<style lang="less" scoped>
.showPosition {
  font-size: 14px;
  font-weight: bold;
  display: flex;
  justify-content: space-between;
}
/deep/.ant-select-tree-node-content-wrapper span {
  color: rgba(0, 0, 0, 0.65) !important;
}
// /deep/.ant-modal-wrap {
//   z-index: 9999;
//   border: solid 1px red;
// }
</style>
